<?php

namespace app\home\controller;

use app\home\model\TradeLog;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\Request;

class Pay800015 extends BasePay
{
    const KEY = '7D2EFB87EE1A3CF064F4F7F95254EDDA';
    const APPID = '2479670';


    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function authenticateUserTicket()
    {
        $params = Request::instance()->param();
        $url = 'https://partner.steam-api.com/ISteamUserAuth/AuthenticateUserTicket/v1?key=' . self::KEY . '&appid=' . self::APPID . '&ticket=' . $params['ticket'];
        $res = $this->getCurl($url);
        exit($res);
    }
    public function getCurl($url)
    {
        $curl  =  curl_init();
        curl_setopt($curl, CURLOPT_URL,  $url);
        curl_setopt($curl, CURLOPT_HEADER,  0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,  1);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        $data  =  curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    public function order()
    {
        $params = Request::instance()->param();
        parent::order();
        $url = 'https://partner.steam-api.com/ISteamMicroTxn/InitTxn/v3/';
        // $url = 'https://partner.steam-api.com/ISteamMicroTxnSandbox/InitTxn/v3/';
        try {
            //TODO 由于这个渠道特殊 订单号和系统成功的长度限制  单号截取2位特殊处理
            $orderid = substr($this->order_array['id'], 0, -2);
            TradeLog::where('id', $this->order_array['id'])->update(['id' => $orderid]);

            //ip限制查不到城市地址一律不支付
               $ip = $_SERVER["REMOTE_ADDR"];
               mylog('Pay800015-ip:'.$ip);

            //    $LastLoginIPurl = 'https://v.apistore.cn/api/ip/globalipsenior?key=zL7dkGXwt6frqKuTrRtKDDzskR0y4nAR&ip='.$ip;
            //    $LastLoginIPinfo = file_get_contents($LastLoginIPurl);
            //    mylog($LastLoginIPinfo);
            //    if (empty(json_decode($LastLoginIPinfo,true)['result']['prov'])){
            //        exit();
            //    }

            //    if (json_decode($LastLoginIPinfo,true)['result']['prov'] == '华盛顿'){
            //        exit();
            //    }

        

            $json_string = file_get_contents(env('PLATFORM.USD'));
            $config = json_decode($json_string, true);
            $usd  = $config[$this->order_array['goods_id']];
            if (empty($usd)) {
                mylog('计费点对应的美元金额找不到');
                return false;
            }


            $data = [
                'key' => self::KEY,
                'appid' => self::APPID,
                'orderid' => $orderid,
                'steamid' => $params['steamid'],
                'itemid[0]' => $this->order_array['goods_id'],
                'amount[0]' => $usd['Mpay'] * 100,
                'description[0]' => empty($usd['title'])?'good_name':$usd['title'],
                'qty[0]' => '1',
                'itemcount' => '1',
                'language' => 'en',
                'currency' => 'USD',
            ];

            $obj = $this->post($url, $data);
            $res = json_decode($obj, true);
            if ($res['response']['result'] != 'OK') {
                throw new \Exception($obj);
            }

            exit(json_encode(['code' => 200, 'msg' => '交易成功', 'data' => ['orderid' => $orderid, 'amount' => $this->order_array['amount']]]));
        } catch (\Exception $exception) {
            mylog('810 下单失败 error:' . $exception->getMessage() . 'line:' . $exception->getLine());
            exit(json_encode(['code' => 400, 'msg' => '交易失败', 'data' => []]));
        }
    }

    public function notify()
    {
        
        parent::notify();
        //回调数据效验
        $params = $this->params;
        try {
            $url = 'https://partner.steam-api.com/ISteamMicroTxn/FinalizeTxn/v2/';
            // $url = 'https://partner.steam-api.com/ISteamMicroTxnSandbox/FinalizeTxn/v2/';
            $data = [
                'key' => self::KEY,
                'appid' => self::APPID,
                'orderid' => $params['orderid'],
            ];
            $obj = $this->post($url, $data);
            mylog($obj);
            $res = json_decode($obj, true);
            if ($res['response']['result'] != 'OK') {
                throw new \Exception('false');
            }

            //保存微信交易号
            if (!empty($res['response']['params']['transid'])) {
                $tradeLog = (new \app\home\model\TradeLog)->where(['id' => $params['orderid']])->find();
                if ($tradeLog) {
                    $tradeLog->transactionID = $res['response']['params']['transid'];
                    $tradeLog->save();
                }
            }

            $notifyService = new NotifyService();
            $order_info = $notifyService->checkOrder($params['orderid'], $params['amount']);
            if ($order_info == false) {
                throw new \Exception('订单号异常');
            }
            if ($order_info["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("Pay800015订单已经处理过了");
                exit(json_encode(['code' => 200, 'msg' => '订单号处理OK', 'data' => []]));
            }
            // 发货
            if ($notifyService->notifyProcess($order_info) == false) {
                throw new \Exception('notifyProcess');
            }

            exit(json_encode(['code' => 200, 'msg' => '订单号处理OK', 'data' => []]));
        } catch (\Exception $exception) {
            mylog('Pay800015 回调 error:' . $exception->getMessage() . 'line:' . $exception->getLine() . ' file：' . $exception->getFile());
            exit(json_encode(['code' => 400, 'msg' => '回调失败', 'data' => []]));
        }
    }

    private function post($url, $content, $header = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);

        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $response = curl_exec($ch);

        if ($error = curl_error($ch)) {
            die($error);
        }
        curl_close($ch);
        return $response;
    }
}
